package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.entity.GoodsTree;
import com.atguigu.jxc.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author zhmwi
 * @Date 2021/9/4
 * @Dersciption
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;

    //查询分级树
    @Override
    public List<GoodsTree> loadGoodsType() {
        //查询分类表所有数据
        List<GoodsTree> all = goodsDao.selectGoodsTypeAll();
        //查询出一级分类
        List<GoodsTree> collect = all.stream().filter((goodsTree) -> {
            //一级分类
            return goodsTree.getId().intValue() == 1;
        }).map((goodsTree) -> {
            //设置默认有子树
            Map<String,Integer> state= new HashMap<>();
            state.put("state",1);
            goodsTree.setAttributes(state);

            //传递当前的商品分类和全部分类 递归查询出全部的子类
            goodsTree.setChildren(this.getChildren(goodsTree, all));

            if (goodsTree.getChildren().size() == 0){
                //设置无子树
                state.put("state",0);
                goodsTree.setAttributes(state);
            }
            return goodsTree;
        }).collect(Collectors.toList());
        return collect;
    }

    //递归查询当前级别分级树
    private List<GoodsTree> getChildren(GoodsTree root, List<GoodsTree> all) {
        return all.stream().filter((goodsTree)->{
            return goodsTree.getPId() == root.getId();
        }).map((goodsTree)->{
            //子菜单可能还有子菜单,递归查询
            goodsTree.setChildren(this.getChildren(goodsTree,all));
            //设置无子树或有子树
            Map<String,Integer> state= new HashMap<>();
            if (goodsTree.getChildren().size() == 0){
                state.put("state",0);
                goodsTree.setAttributes(state);
            }else{
                state.put("state",1);
                goodsTree.setAttributes(state);
            }
            return goodsTree;
        }).collect(Collectors.toList());
    }


}
